package com.mingmen.canting.jingli;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.mingmen.canting.R;
import com.mingmen.canting.activity.FilterCompareActivity;
import com.mingmen.canting.activity.FilterKuaijieActivity;
import com.mingmen.canting.adapter.JingLiRuKuAdapter;
import com.mingmen.canting.adapter.SearchAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.caigourenyuan.CaiGouWanListActivity;
import com.mingmen.canting.chushizhang.JingLiCompareActivity;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ClearEditText;
import com.mingmen.canting.defineview.DetailsMarkerView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.GongCompareModel;
import com.mingmen.canting.model.JingLiRukuModel;
import com.mingmen.canting.model.SearchModel;
import com.mingmen.canting.model.ShujuModel;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.ScalableCardHelper;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.zhexian.charting.charts.LineChart;
import com.mingmen.canting.zhexian.charting.components.Description;
import com.mingmen.canting.zhexian.charting.components.Legend;
import com.mingmen.canting.zhexian.charting.components.XAxis;
import com.mingmen.canting.zhexian.charting.components.YAxis;
import com.mingmen.canting.zhexian.charting.data.Entry;
import com.mingmen.canting.zhexian.charting.data.LineData;
import com.mingmen.canting.zhexian.charting.data.LineDataSet;
import com.mingmen.canting.zhexian.charting.formatter.ValueFormatter;
import com.scwang.smart.refresh.horizontal.SmartRefreshHorizontal;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

public class JingLiRukuFragment extends Fragment implements ScalableCardHelper.OnPageChangeListener {

    @BindView(R.id.text_count)
    TextView textCount;
    Unbinder unbinder;
    @BindView(R.id.main_search)
    ClearEditText mainSearch;
    @BindView(R.id.layout_search)
    LinearLayout layoutSearch;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;
    @BindView(R.id.rv_photo_list)
    RecyclerView rvPhotoList;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    private String mTitle;

    String token;

    List<JingLiRukuModel.DataBean> dataBeanList = new ArrayList<>();
    JingLiRuKuAdapter jingLiRuKuAdapter;
    //    List<JingLiRukuModel.DataBean.DetailsBean> detailsBeanList = new ArrayList<>();
    @BindView(R.id.text_compare)
    TextView text_compare;

    List<ShujuModel.DataBean> compareDataBeanList = new ArrayList<>();
    private int resurtResurant = 100;
    private int kuaijie = 100;
    String string = "{\"code\":0,\"message\":\"操作成功\",\"time\":\"2020-08-07 16:05:32\",\"data\":[{\"priceDate\":\"2020-08-01\",\"price\":200.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-02\",\"price\":210.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-03\",\"price\":250.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-04\",\"price\":180.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-05\",\"price\":300.00,\"maxPrice\":300.00,\"minPrice\":180.00},{\"priceDate\":\"2020-08-06\",\"price\":200.00,\"maxPrice\":300.00,\"minPrice\":180.00}]}";

    @BindView(R.id.layout_calendafirst)
    LinearLayout layout_calendafirst;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;
    @BindView(R.id.layout_lineChart)
    LinearLayout layout_lineChart;
    TimePickerView pvTime;
    String startTime = "";
    String endTime = "";

    @BindView(R.id.layout_dingdan)
    LinearLayout layout_dingdan;


    @BindView(R.id.refreshLayout)
    SmartRefreshHorizontal refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    String commodityId = "";
    @BindView(R.id.layout_topopen)
    LinearLayout layout_topopen;
    List<Entry> listOne = new ArrayList<>();
    @BindView(R.id.lineChart)
    LineChart lineChart;
    XAxis xAxis;
    LineDataSet one;
    YAxis axisLeft;
    @BindView(R.id.btn_digndan)
    Button btn_digndan;
    @BindView(R.id.btn_suofang)
    Button btnSuofang;
    @BindView(R.id.img_list)
    ImageView imgList;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jingliruku, null);
        unbinder = ButterKnife.bind(this, view);
        TextView card_title_tv = (TextView) view.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);

        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_photo_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
//        recyclerView.setAdapter(new JingLiRuKuAdapter(getActivity(), dataBeanList));
        jingLiRuKuAdapter = new JingLiRuKuAdapter(getActivity(), dataBeanList);
        recyclerView.setAdapter(jingLiRuKuAdapter);

        ScalableCardHelper cardHelper = new ScalableCardHelper(this);
        cardHelper.attachToRecyclerView(recyclerView);
        getCaneda();
        jingLiRuKuAdapter.setOnItemClickListener(new JingLiRuKuAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, List<JingLiRukuModel.DataBean> mList, List<JingLiRukuModel.DataBean.DetailsBean> mNewList) {
                Intent intent;
                switch (view.getId()) {
                    case R.id.layout_jump:

                        intent = new Intent(getActivity(), CaiGouWanListActivity.class);


                        break;
                }
            }
        });


        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;


        String replace_data = data.replace("-", ".");
        Log.d("replace_data", replace_data);
        textview_calendafirst.setText(replace_data);
        textview_calendasecond.setText(replace_data);

//        getData(token, "1", startTime, endTime, pageNumber, "");
        getData(token, "1", "", "", pageNumber, commodityId);
        mainSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    commodityId = "";

                } else if (s.toString().length() < 1) {
                    commodityId = "";

                } else {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            PopupWindow popupWindow = new PopupWindowCompat(getActivity());
                            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_search, null);
                            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                            popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                            popupWindow.setContentView(contentView);
                            popupWindow.setOutsideTouchable(true);
                            popupWindow.setFocusable(true);
                            popupWindow.setBackgroundDrawable(new BitmapDrawable());
                            TextView textView = contentView.findViewById(R.id.tv_kdd);
                            textView.setText("");
                            LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
                            layout_content.getBackground().setAlpha(180);
                            SwipeRecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);
                            List<SearchModel.DataBean> searchList = new ArrayList<>();
                            if (searchList.size() > 0) {
                                searchList.clear();
                            }

                            HttpResponse.queryCommodity(token, mainSearch.getText().toString(), new StringCallback(getActivity()) {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    SearchModel searchModel = new SearchModel();
                                    searchModel = GsonUtil.GsonToBean(s, SearchModel.class);
                                    searchList.addAll(searchModel.getData());
                                    InputMethodManager imm = (InputMethodManager) getActivity()
                                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
                                    if (searchList.size() > 0) {
                                        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                                        SearchAdapter myLabelAdapter = new SearchAdapter(getActivity(), searchList);
                                        recyclerView.setAdapter(myLabelAdapter);
                                        myLabelAdapter.setDataList(searchList);
                                        popupWindow.showAsDropDown(layoutSearch);
//                                        popupWindow.dismiss();
                                        myLabelAdapter.setOnItemClickListener(new SearchAdapter.OnItemClickListener() {
                                            @Override
                                            public void onItemClickListener(View view, int pos, List<SearchModel.DataBean> myLiveList) {
                                                myLabelAdapter.setCheckedPosition(pos);
                                                dataBeanList.clear();
//                                                mainSearch.setText(myLiveList.get(pos).getCommodityName());
                                                commodityId = myLiveList.get(pos).getCommodityId();
                                                popupWindow.dismiss();

                                            }


                                        });
                                        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
                                        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));

                                        recyclerView.addItemDecoration(divider);

                                    } else {
                                        Toast.makeText(getActivity(), "当前搜索无数据", Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });


                        }
                    }, 800);
                }


//                startActivityForResult(intent, resurtResurant);
            }
        });

        mainSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                PopupWindow popupWindow = new PopupWindowCompat(getActivity());
                View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_search, null);
                popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                popupWindow.setContentView(contentView);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                TextView textView = contentView.findViewById(R.id.tv_kdd);
                textView.setText("");
                LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
                layout_content.getBackground().setAlpha(180);
                SwipeRecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);
                List<SearchModel.DataBean> searchList = new ArrayList<>();
                if (searchList.size() > 0) {
                    searchList.clear();
                }

                HttpResponse.queryCommodity(token, mainSearch.getText().toString(), new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        SearchModel searchModel = new SearchModel();
                        searchModel = GsonUtil.GsonToBean(s, SearchModel.class);
                        searchList.addAll(searchModel.getData());
                        if (searchList.size() > 0) {
                            InputMethodManager imm = (InputMethodManager) getActivity()
                                    .getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);

                            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                            SearchAdapter myLabelAdapter = new SearchAdapter(getActivity(), searchList);
                            recyclerView.setAdapter(myLabelAdapter);
                            myLabelAdapter.setDataList(searchList);
                            popupWindow.dismiss();

                            myLabelAdapter.setOnItemClickListener(new SearchAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClickListener(View view, int pos, List<SearchModel.DataBean> myLiveList) {
                                    popupWindow.dismiss();
                                    myLabelAdapter.setCheckedPosition(pos);
                                    dataBeanList.clear();
//                                                mainSearch.setText(myLiveList.get(pos).getCommodityName());
                                    commodityId = myLiveList.get(pos).getCommodityId();
                                    popupWindow.dismiss();
                                    getData(token, "1", startTime, endTime, pageNumber, commodityId);

                                }


                            });
                            DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
                            divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));

                            recyclerView.addItemDecoration(divider);
                            Intent intent = new Intent(getActivity(), JingLiCompareActivity.class);
                            intent.putExtra("logindata", s);
                        } else {
                            Toast.makeText(getActivity(), "当前搜索无数据", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

                return false;
            }
        });

        Gson gson = new Gson();

        ShujuModel shujuModel = gson.fromJson(string, ShujuModel.class);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, "1", startTime, endTime, pageNumber, "");
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;
                    getData(token, "1", startTime, endTime, pageNumber, commodityId);

                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });

        return view;
    }

    public void getData(String token, String st, String startTime, String endTime, int pageNumber, String commodityId) {
        HttpResponse.getConsumeBillList(token, st, startTime, endTime, pageNumber, commodityId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("JingLiRukuFragment", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    JingLiRukuModel jingLiRukuModel = new JingLiRukuModel();
                    jingLiRukuModel = GsonUtil.GsonToBean(s, JingLiRukuModel.class);
                    dataBeanList.addAll(jingLiRukuModel.getData());
                    if (dataBeanList.size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                        layout_alldata.setVisibility(View.GONE);
                        layout_topopen.setVisibility(View.GONE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                        layout_alldata.setVisibility(View.VISIBLE);
                        layout_topopen.setVisibility(View.VISIBLE);
                    }
//                jingLiRuKuAdapter.setDataList(jingLiRukuModel.getData());
                    jingLiRuKuAdapter.setDataList(dataBeanList);
                    textCount.setText(jingLiRukuModel.getCount() + "");
                    totalPage = jingLiRukuModel.getTotalPage();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_topopen.setVisibility(View.GONE);
                layout_nodata.setVisibility(View.VISIBLE);
                layout_alldata.setVisibility(View.GONE);
            }
        });
    }

    public static JingLiRukuFragment getInstance(String title) {
        JingLiRukuFragment sf = new JingLiRukuFragment();
        sf.mTitle = title;
        return sf;
    }

    int mypositon = 0;

    @Override
    public void onPageSelected(int position) {
        mypositon = position;
        Log.d("kdkkckkc", mypositon + "");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.main_search, R.id.layout_search, R.id.text_compare, R.id.layout_calendafirst, R.id.layout_calenda_second, R.id.layout_dingdan, R.id.textview_calendafirst, R.id.textview_calendasecond,R.id.btn_digndan,R.id.btn_suofang,R.id.img_list})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.main_search:

                break;
            case R.id.layout_search:
                break;
            case R.id.text_compare:
                Log.d("TextCompare", compareDataBeanList.size() + "");

                if (TextUtils.isEmpty(commodityId)) {
                    Toast.makeText(getActivity(), "请选择商品", Toast.LENGTH_SHORT).show();
                } else {
                    HttpResponse.comparePriceLine(token, startTime, endTime, commodityId, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("comparePriceLine", s);

                            List<String> arriveDate = new ArrayList<>();

                            GongCompareModel gongCompareModel = new GongCompareModel();
                            gongCompareModel = GsonUtil.GsonToBean(s, GongCompareModel.class);
                            List<GongCompareModel.DataBean.PriceListBean> priceListBeans = new ArrayList<>();

                            List<GongCompareModel.DataBean.PriceListBean.SubPriceLineBean> subPriceLineBeanArrayList = new ArrayList<>();


                            if (priceListBeans.size() > 0) {
                                priceListBeans.clear();
                            }
                            priceListBeans = gongCompareModel.getData().get(0).getPriceList();

                            for (int i = 0; i < priceListBeans.size(); i++) {
                                if (priceListBeans.get(i).getSubPriceLine().size() == 0) {

                                } else {
                                    subPriceLineBeanArrayList.addAll(priceListBeans.get(i).getSubPriceLine());
                                }

                            }

                            if (subPriceLineBeanArrayList.size() == 0) {
                                layout_lineChart.setVisibility(View.GONE);
                                layout_nodata.setVisibility(View.VISIBLE);
                                Toast.makeText(getActivity(), "当前无比价信息", Toast.LENGTH_SHORT).show();
                            } else {

                                if (priceListBeans.size() == 0) {
                                    layout_lineChart.setVisibility(View.GONE);
                                    layout_nodata.setVisibility(View.VISIBLE);
                                } else {
                                    if (priceListBeans.size() > 0) {
                                        layout_nodata.setVisibility(View.GONE);
                                        layout_alldata.setVisibility(View.GONE);
                                        layout_lineChart.setVisibility(View.VISIBLE);
                                        arriveDate.clear();
                                        listOne.clear();
                                    } else {
                                        layout_lineChart.setVisibility(View.GONE);

                                    }

                                    for (int i = 0; i < priceListBeans.size(); i++) {
                                        arriveDate.add(priceListBeans.get(i).getArriveDate());
                                    }

                                    for (int i = 0; i < priceListBeans.size(); i++) {
                                        listOne.add(new Entry(i, priceListBeans.get(i).getPrice()));
                                    }
                                    Legend legend = lineChart.getLegend();
                                    legend.setEnabled(false);

                                    one = new LineDataSet(listOne, "One");//将数据赋值到你的线条上

                                    one = new LineDataSet(listOne, "");//将数据赋值到你的线条上

                                    one.setColor(Color.parseColor("#626666"));//设置线的颜色
//        one.setColor(Color.DKGRAY);
                                    // 显示的圆形的大小
                                    one.setCircleSize(5.0f);
                                    // 圆球的颜色
//        #BA0017
//        one.setCircleColor(Color.GREEN);
                                    one.setCircleColor(getResources().getColor(R.color.normal_red));
                                    one.setCircleHoleColor(getResources().getColor(R.color.normal_red));
                                    one.setDrawValues(false);
                                    one.setDrawFilled(false); //设置折线图下方颜色填充默认是蓝色

                                    one.setDrawHighlightIndicators(false);
                                    // 点击后，十字交叉线的颜色
                                    one.setHighLightColor(Color.TRANSPARENT);
                                    LineData lineData = new LineData();// //线的总管理
                                    lineData.addDataSet(one);//每加一条就add一次
                                    lineChart.setData(lineData);//把线条设置给你的lineChart上
                                    lineChart.invalidate();//刷新

                                    xAxis = lineChart.getXAxis();//得到x轴
                                    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的位置，在整个图形的底部
                                    xAxis.setLabelCount(listOne.size(), false); //设置X轴刻度 第一个参数是想要x轴有多少条刻度,第二个参数true是将刻度数设置为你的第一个参数的数量 ，false是将刻度数设置为你的第一个参数的数量+1（0.0点也要算哦）
                                    xAxis.setGranularity(1f);//设置x轴坐标间的最小间距
                                    xAxis.setAxisMaximum(listOne.size() - 1);//设置x轴的最大范围
                                    xAxis.setAxisMinimum(0f);//设置x轴的最小范围
//        xAxis.setYOffset(50f);
                                    xAxis.setDrawGridLines(true);//绘制网格线
                                    xAxis.setAxisLineWidth(1.5f);


                                    xAxis.setValueFormatter(new ValueFormatter() {

                                        @Override
                                        public String getFormattedValue(float value) {
                                            Log.d("valuex", (int) value + "");

                                            if ((int) value == 0) {
                                                one.setCircleColor(getResources().getColor(R.color.transparent));
                                                return "";
                                            } else {
                                                one.setCircleColor(getResources().getColor(R.color.normal_red));
                                                //设置是否绘制刻度
                                                xAxis.setDrawScale(true);

                                                return arriveDate.get((int) value);

                                            }
                                        }
                                    });

///取消左下角描述
                                    lineChart.getDescription().setEnabled(true);

                                    Description description = new Description();
                                    description.setText("时间");
                                    lineChart.setDescription(description);
                                    //Y轴不是有左右两边嘛，这就是获取左右两边的y轴
                                    YAxis left = lineChart.getAxisLeft();
                                    //是否绘制0所在的网格线/默认false绘制
                                    left.setDrawGridLines(true);//绘制网格线
                                    left.setDrawZeroLine(true);
                                    //将网格线设置为虚线模式
//        left.enableGridDashedLine(10f, 10f, 0f);
                                    //获取图表右边y轴
                                    YAxis right = lineChart.getAxisRight();
                                    //禁用图表右边y轴
                                    right.setEnabled(false);

                                    YAxis axisRight = lineChart.getAxisRight();
                                    axisLeft = lineChart.getAxisLeft();
                                    axisRight.setEnabled(false);//将右边的y轴隐藏
                                    //y轴最大值最小值范围
//        axisLeft.setAxisMaximum(550f);
                                    axisLeft.setDrawGridLines(true);
//        axisLeft.setAxisMaximum(15);
                                    axisLeft.setAxisMaximum(20f);
                                    axisLeft.setAxisMinimum(0f);
//        axisLeft.setLabelCount(3, true);

                                    //文字颜色
                                    axisLeft.setTextColor(Color.parseColor("#000000"));//设置左y轴字的颜色
                                    axisLeft.setAxisLineColor(Color.BLACK);//y轴颜色
                                    axisLeft.setDrawZeroLine(true); // draw a zero line
                                    axisLeft.setZeroLineColor(Color.GRAY);
                                    axisLeft.setZeroLineWidth(1.5f);
                                    axisLeft.setAxisLineWidth(1.5f);
                                    axisLeft.setAxisLineColor(Color.GRAY);
                                    axisLeft.setMinWidth(5f);
//        axisLeft.setDrawTopYLabelEntry(false);
                                    axisLeft.setValueFormatter(new
                                                                       ValueFormatter() {
                                                                           @Override
                                                                           public String getFormattedValue(float value) {
                                                                               xAxis.setDrawScale(true);
                                                                               axisLeft.setDrawScale(true);
                                                                               if (value == 0) {
                                                                                   return "";
                                                                               } else {
                                                                                   return super.getFormattedValue(value);
                                                                               }


                                                                           }
                                                                       });

                                    Matrix m = new Matrix();
//        m.postScale(3.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
                                    m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
                                    lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

                                    lineChart.animateX(1000); // 立即执行的动画,x轴
                                    lineChart.setDragEnabled(true);// 是否可以拖拽

                                    lineChart.setScaleEnabled(false);// 是否可以缩放 x和y轴, 默认是true
                                    lineChart.setScaleXEnabled(false); //是否可以缩放 仅x轴
                                    lineChart.setScaleYEnabled(false); //是否可以缩放 仅y轴

                                    axisLeft.setDrawTopYLabelEntry(false);
                                    axisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
                                    List<GongCompareModel.DataBean.PriceListBean> finalPriceListBeans = priceListBeans;
                                    DetailsMarkerView detailsMarkerView = new DetailsMarkerView(getActivity(), new ValueFormatter() {
                                        @Override
                                        public String getFormattedValue(float value) {
                                            Log.d("mark", "mark" + value);
//                                priceListBeans.get(value).getSubPriceLine();
                                            Intent intent = new Intent(getActivity(), FilterCompareActivity.class);

                                            int position = (int) value;
                                            intent.putExtra("subPriceLine", MyStringUtils.beanToString(finalPriceListBeans.get(position).getSubPriceLine()));

                                            startActivity(intent);

                                            return super.getFormattedValue(value);
                                        }
                                    });

                                    detailsMarkerView.setChartView(lineChart);
                                    lineChart.setMarker(detailsMarkerView);
                                }


                            }


                        }
                    });
                }

                break;
            case R.id.layout_calendafirst:
            case R.id.textview_calendafirst:
                pvTime.show(layout_calendafirst);
                pvTime.show(textview_calendafirst);
                break;
            case R.id.layout_calenda_second:
            case R.id.textview_calendasecond:
                pvTime.show(layout_calenda_second);
                pvTime.show(textview_calendasecond);
                break;
            case R.id.layout_dingdan:
//                startActivity(new Intent(getActivity(), FilterKuaijieActivity.class));

                rvPhotoList.setVisibility(View.VISIBLE);
                layout_lineChart.setVisibility(View.GONE);

                intent = new Intent(getActivity(), FilterKuaijieActivity.class);

                intent.putExtra("count", textCount.getText().toString());
                intent.putExtra("kuaijie", "10");
                startActivityForResult(intent, kuaijie);
                break;
            case R.id.btn_digndan:
//                startActivity(new Intent(getActivity(), JingLiDingDanActivity.class));
                startActivity(new Intent(getActivity(), JingLiNewDingDanActivity.class));
                break;
            case R.id.btn_suofang:
                btn_digndan.setVisibility(View.GONE);
                btnSuofang.setVisibility(View.VISIBLE);
                imgList.setVisibility(View.VISIBLE);
                break;
            case R.id.img_list:
                imgList.setVisibility(View.GONE);
                btn_digndan.setVisibility(View.VISIBLE);
                btnSuofang.setVisibility(View.VISIBLE);
                break;
        }
    }


    String commodityName;
    String receiveposition;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
//            Toast.makeText(getActivity(), resultCode+"", Toast.LENGTH_SHORT).show();
            receiveposition = data.getStringExtra("jingliruku");
            int mysmooth = Integer.valueOf(receiveposition);
            rvPhotoList.scrollToPosition(mysmooth);
        } else if (resultCode == 100) {
            try {
                commodityId = data.getStringExtra("commodityId");
                commodityName = data.getStringExtra("commodityName");
                mainSearch.setText(commodityName);
                Log.d("ckkckc", commodityId + commodityName);
            } catch (Exception e) {

            }
        }


    }


    public void getCaneda() {
   /*     Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(y, m, d);*/
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(2033, 12, 31);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_calendafirst:
                    case R.id.textview_calendafirst:
//                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);
                        Integer i = startTime.compareTo(endTime);
                        String replace_data = getTime(date).replace("-", ".");
                        Log.d("replace_data", replace_data);
                        textview_calendafirst.setText(replace_data);
                        if (i > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            String replace_data1 = getTime(date).replace("-", ".");
                            Log.d("replace_data", replace_data1);
                            textview_calendasecond.setText(replace_data1);
                            getData(token, "1", startTime, endTime, pageNumber, commodityId);
                        }

                        break;
                    case R.id.layout_calenda_second:
                    case R.id.textview_calendasecond:
                        endTime = getTime(date);
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            textview_calendasecond.setText(getTime(date));
                            getData(token, "1", startTime, endTime, pageNumber, commodityId);
                        }

                        break;
                }


            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });


                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
